local mianyao = fk.CreateSkill {
  name = "mianyao",
}

Fk:loadTranslationTable{
  ["mianyao"] = "免徭",
  [":mianyao"] = "摸牌阶段结束时，你可以将手牌中点数最小的一张牌随机置入牌堆，然后于本回合结束时摸X张牌（X为此牌的点数）。",

  ["#mianyao-invoke"] = "免徭：将一张点数最小的手牌置入牌堆，回合结束时摸牌",
  ["@mianyao"] = "免徭",

  ["$mianyao1"] = "缮舫厉甲，以定六郡之地。",
  ["$mianyao2"] = "筑连舫之众，成一统之业。",
}

mianyao:addEffect(fk.EventPhaseEnd, {
  anim_type = "special",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(mianyao.name) and player.phase == Player.Draw and
      not player:isKongcheng()
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local ids = table.filter(player:getCardIds("h"), function(id)
      return table.every(player:getCardIds("h"), function(id2)
        return Fk:getCardById(id).number <= Fk:getCardById(id2).number
      end)
    end)
    local cards = room:askToCards(player, {
      skill_name = mianyao.name,
      min_num = 1,
      max_num = 1,
      include_equip = false,
      pattern = tostring(Exppattern{ id = ids }),
      prompt = "#mianyao-invoke",
    })
    if #cards > 0 then
      room:moveCards({
        ids = cards,
        from = player,
        toArea = Card.DrawPile,
        moveReason = fk.ReasonJustMove,
        skill_name = mianyao.name,
        drawPilePosition = math.random(#room.draw_pile),
      })
    else
      return mianyao.name
    end
    --[[local x = 0
    for _, move in ipairs(data) do
      if move.from == player then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerHand and
            room:removeTableMark(player, mianyao.name, info.cardId) then
            x = x + Fk:getCardById(info.cardId).number
          end
        end
      end
    end
    if x > 0 then
    player.room:addPlayerMark(player, "@mianyao", x)
    end]]
    local x = 0
    for _, id in ipairs(cards) do
      x = x + Fk:getCardById(id).number
    end
    if x > 0 then
    player.room:addPlayerMark(player, "@mianyao", x)
    end
  end,
})

mianyao:addEffect(fk.EventPhaseStart, {
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(mianyao.name) and player.phase == Player.Finish and
    player:getMark("@mianyao") > 0
  end,
  on_cost = Util.TrueFunc,
    cancelable = false,
  on_use = function(self, event, target, player, data)
    local targets = {}
    local n = player:getMark("@mianyao")
    player:drawCards(n, mianyao.name)
    player.room:setPlayerMark(player, "@mianyao", 0)
  end,
})

mianyao:addLoseEffect(function (self, player, is_death)
  player.room:setPlayerMark(player, mianyao.name, 0)
end)

return mianyao
